package edu.study.common.util.math;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 类MoneyUtils.java的实现描述：
 *
 * @author liujia 2017年1月9日 上午11:06:16
 */
public class MoneyUtil {
    /**
     * 大写数字
     */
    private static final String[] NUMBERS = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
    /**
     * 整数部分的单位
     */
    private static final String[] IUNIT = {"元", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "万", "拾", "佰", "仟"};
    /**
     * 小数部分的单位
     */
    private static final String[] DUNIT = {"角", "分", "厘"};

    /**
     * 得到大写金额。
     */
    public static String toChinese(String str) {
        str = str.replaceAll(",", "");// 去掉","
        String integerStr;// 整数部分数字
        String decimalStr;// 小数部分数字

        // 初始化：分离整数部分和小数部分
        if (str.indexOf(".") > 0) {
            integerStr = str.substring(0, str.indexOf("."));
            decimalStr = str.substring(str.indexOf(".") + 1);
        } else if (str.indexOf(".") == 0) {
            integerStr = "";
            decimalStr = str.substring(1);
        } else {
            integerStr = str;
            decimalStr = "";
        }
        // integerStr去掉首0，不必去掉decimalStr的尾0(超出部分舍去)
        if (!integerStr.equals("")) {
            integerStr = Long.toString(Long.parseLong(integerStr));
            if (integerStr.equals("0")) {
                integerStr = "";
            }
        }
        // overflow超出处理能力，直接返回
        if (integerStr.length() > IUNIT.length) {
            System.out.println(str + ":超出处理能力");
            return str;
        }

        int[] integers = toArray(integerStr);// 整数部分数字
        boolean isMust5 = isMust5(integerStr);// 设置万单位
        int[] decimals = toArray(decimalStr);// 小数部分数字
        return getChineseInteger(integers, isMust5) + getChineseDecimal(decimals);
    }

    /**
     * 整数部分和小数部分转换为数组，从高位至低位
     */
    private static int[] toArray(String number) {
        int[] array = new int[number.length()];
        for (int i = 0; i < number.length(); i++) {
            array[i] = Integer.parseInt(number.substring(i, i + 1));
        }
        return array;
    }

    /**
     * 得到中文金额的整数部分。
     */
    private static String getChineseInteger(int[] integers, boolean isMust5) {
        StringBuffer chineseInteger = new StringBuffer("");
        int length = integers.length;
        for (int i = 0; i < length; i++) {
            // 0出现在关键位置：1234(万)5678(亿)9012(万)3456(元)
            // 特殊情况：10(拾元、壹拾元、壹拾万元、拾万元)
            String key = "";
            if (integers[i] == 0) {
                if ((length - i) == 13) // 万(亿)(必填)
                    key = IUNIT[4];
                else if ((length - i) == 9) // 亿(必填)
                    key = IUNIT[8];
                else if ((length - i) == 5 && isMust5) // 万(不必填)
                    key = IUNIT[4];
                else if ((length - i) == 1) // 元(必填)
                    key = IUNIT[0];
                // 0遇非0时补零，不包含最后一位
                if ((length - i) > 1 && integers[i + 1] != 0)
                    key += NUMBERS[0];
            }
            chineseInteger.append(integers[i] == 0 ? key : (NUMBERS[integers[i]] + IUNIT[length - i - 1]));
        }
        return chineseInteger.toString();
    }

    /**
     * 得到中文金额的小数部分。
     */
    private static String getChineseDecimal(int[] decimals) {
        StringBuffer chineseDecimal = new StringBuffer("");
        for (int i = 0; i < decimals.length; i++) {
            // 舍去3位小数之后的
            if (i == 3)
                break;
            chineseDecimal.append(decimals[i] == 0 ? "" : (NUMBERS[decimals[i]] + DUNIT[i]));
        }
        return chineseDecimal.toString();
    }

    /**
     * 判断第5位数字的单位"万"是否应加。
     */
    private static boolean isMust5(String integerStr) {
        int length = integerStr.length();
        if (length > 4) {
            String subInteger = "";
            if (length > 8) {
                // 取得从低位数，第5到第8位的字串
                subInteger = integerStr.substring(length - 8, length - 4);
            } else {
                subInteger = integerStr.substring(0, length - 4);
            }
            return Integer.parseInt(subInteger) > 0;
        } else {
            return false;
        }
    }

    /**
     * 把null当作0处理
     */
    public static BigDecimal null2Zero(Number amount) {
        if (amount == null)
            return BigDecimal.ZERO;

        if (amount instanceof BigDecimal) {
            return (BigDecimal) amount;
        } else {
            return new BigDecimal(amount.toString());
        }
    }

    /**
     * 判断金额是否为“零”值
     */
    public static boolean isZero(Number amount) {
        return null2Zero(amount).compareTo(BigDecimal.ZERO) == 0;
    }

    /**
     * 判断金额是否大于零
     */
    public static boolean greaterThanZero(Number amount) {
        return null2Zero(amount).compareTo(BigDecimal.ZERO) > 0;
    }

    /**
     * 取两个数字的最大值
     */
    public static BigDecimal max(Number amount1, Number amount2) {
        if (null2Zero(amount1).compareTo(null2Zero(amount2)) > 0) {
            return null2Zero(amount1);
        } else {
            return null2Zero(amount2);
        }
    }

    /**
     * 判断金额是否小于零
     */
    public static boolean lessThanZero(Number amount) {
        return null2Zero(amount).compareTo(BigDecimal.ZERO) < 0;
    }

    /**
     * 两个金额比较
     */
    public static int compare(Number m1, Number m2) {
        return null2Zero(m1).compareTo(null2Zero(m2));
    }

    /**
     * 多个金额相加，至少2个参数
     */
    public static BigDecimal add(Number amount1, Number amount2, Number... amounts) {
        BigDecimal result = null2Zero(amount1).add(null2Zero(amount2));
        for (Number amount : amounts) {
            result = result.add(null2Zero(amount));
        }
        return result;
    }

    /**
     * 多个金额相乘，至少2个参数，不处理精度
     */
    public static BigDecimal multiply(Number amount1, Number amount2, Number... amounts) {
        BigDecimal result = null2Zero(amount1).multiply(null2Zero(amount2));
        for (Number amount : amounts) {
            result = result.multiply(null2Zero(amount));
        }
        return result;
    }

    /**
     * 多个金额相乘，至少2个参数，四舍五入保留两位小数
     */
    public static BigDecimal multiplyWithScale(RoundingMode mode, Number amount1, Number amount2, Number... amounts) {
        BigDecimal result = null2Zero(amount1).multiply(null2Zero(amount2));
        for (Number amount : amounts) {
            result = result.multiply(null2Zero(amount));
        }
        result = result.setScale(2, mode);
        return result;
    }

    /**
     * 多个金额相乘，至少2个参数，四舍五入保留两位小数
     */
    public static BigDecimal multiplyWithScale(RoundingMode mode, Integer scale, Number amount1, Number amount2, Number... amounts) {
        BigDecimal result = null2Zero(amount1).multiply(null2Zero(amount2));
        for (Number amount : amounts) {
            result = result.multiply(null2Zero(amount));
        }
        result = result.setScale(scale, mode);
        return result;
    }

    /**
     * 多个金额相乘，至少2个参数，四舍五入保留两位小数
     */
    public static BigDecimal multiplyWithScale(Number amount1, Number amount2, Number... amounts) {
        BigDecimal result = null2Zero(amount1).multiply(null2Zero(amount2));
        for (Number amount : amounts) {
            result = result.multiply(null2Zero(amount));
        }
        result = result.setScale(2, RoundingMode.HALF_UP);
        return result;
    }

    /**
     * 金额相减
     *
     * @param amount1
     * @param amount2
     * @return
     */
    public static BigDecimal subtract(Number amount1, Number amount2) {
        return null2Zero(amount1).subtract(null2Zero(amount2));
    }

    /**
     * 多个金额相减，至少2个参数
     */
    public static BigDecimal subtract(Number amount1, Number amount2, Number... amounts) {
        BigDecimal result = null2Zero(amount1).subtract(null2Zero(amount2));
        for (Number amount : amounts) {
            result = result.subtract(null2Zero(amount));
        }
        return result;
    }

    /**
     * 对两个金额做除法（不丢失精度），四舍五入保留指定位数的小数
     *
     * @param src
     * @param dest
     * @param scale 保留位数
     */
    public static BigDecimal divide(Number src, Number dest, int scale) {
        BigDecimal srcDeci = null2Zero(src);
        BigDecimal destDeci = null2Zero(dest);
        return srcDeci.divide(destDeci, scale, RoundingMode.HALF_UP);
    }

    /**
     * 对两个金额做除法（不丢失精度），指定RoundingMode
     *
     * @param src
     * @param dest
     * @param scale 保留位数
     */
    public static BigDecimal divide(Number src, Number dest, int scale, RoundingMode mode) {
        BigDecimal srcDeci = null2Zero(src);
        BigDecimal destDeci = null2Zero(dest);
        return srcDeci.divide(destDeci, scale, mode);
    }

    /**
     * 金额单位元转分
     */
    public static BigDecimal yuan2Fen(BigDecimal amount) {
        if (amount == null) {
            return BigDecimal.ZERO;
        }
        return amount.movePointRight(2).setScale(0, BigDecimal.ROUND_DOWN);
    }

    /**
     * 金额单位分转元
     */
    public static BigDecimal fen2yuan(BigDecimal amount) {
        return null2Zero(amount).movePointLeft(2).setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    /**
     * 检查是否是正确的资金金额
     *
     * @param val
     * @return
     */
    public static boolean checkValidAmount(BigDecimal val) {
        if (null == val) {
            return true;
        }

        BigDecimal result = val.setScale(2, RoundingMode.DOWN);
        return result.compareTo(val) == 0;
    }

    /**
     * NPV公式，用于计算现值PV，保留6位小数，四舍五入
     *
     * @param perNCF     每期的净现金流(除最后一期外)
     * @param perRate    收益率
     * @param periods    期数
     * @param lastPerNCF 最后一期的净现金流
     * @return
     */
    public static BigDecimal calPv(BigDecimal perNCF, BigDecimal perRate, int periods, BigDecimal lastPerNCF) {
        BigDecimal result = BigDecimal.ZERO;
        for (int i = 1; i <= periods - 1; i++) {
            result = result.add(perNCF.divide(perRate.add(BigDecimal.ONE).pow(i), 8, RoundingMode.DOWN));
        }
        result = result.add(lastPerNCF.divide(perRate.add(BigDecimal.ONE).pow(periods), 8, RoundingMode.DOWN));
        result = result.divide(new BigDecimal("1"), 6, RoundingMode.HALF_UP);
        return result;
    }

    /**
     * PMT公式，用于计算每期净现金流NCF，保留6位小数，四舍五入
     *
     * @param firstFlow 期初现金流出
     * @param perRate   收益率
     * @param periods   期数
     * @return
     */
    public static BigDecimal calEachNcf(BigDecimal firstFlow, BigDecimal perRate, int periods) {
        BigDecimal divisor = firstFlow.multiply(perRate.add(BigDecimal.ONE).pow(periods));
        BigDecimal dividend = BigDecimal.ZERO;
        BigDecimal result = BigDecimal.ZERO;
        for (int i = 0; i < periods; i++) {
            dividend = dividend.add(perRate.add(BigDecimal.ONE).pow(i));
        }
        result = divisor.divide(dividend, 6, RoundingMode.HALF_UP);
        return result;
    }

    /**
     * 计算第N期的终值（前提：前几期每期的净现金流必须相等）,保留6位小数，四舍五入
     *
     * @param PV         未来收益的现值
     * @param preEachNcf 前几期每期的净现金流
     * @param perRate    收益率
     * @param periods    当前的期数
     * @return
     */
    public static BigDecimal calFvByPV(BigDecimal PV, BigDecimal preEachNcf, BigDecimal perRate, int periods) {
        BigDecimal result = PV.multiply(perRate.add(BigDecimal.ONE).pow(periods));
        for (int i = 1; i < periods; i++) {
            result = result.subtract(preEachNcf.multiply(perRate.add(BigDecimal.ONE).pow(i)));
        }
        result = result.divide(new BigDecimal("1"), 6, RoundingMode.HALF_UP);
        return result;
    }

    /**
     * 检查分期金额是否合法
     *
     * @param arg0
     * @param arg1
     * @return
     */
    public static boolean checkPeriodAmount(BigDecimal arg0, Integer arg1) {

        if (arg1 > 0) {
            BigDecimal periodAmount = divide(arg0, new BigDecimal(arg1), 2);

            return (periodAmount.compareTo(BigDecimal.ZERO) > 0);
        }

        return true;
    }

    /**
     * 金额精度检查
     *
     * @param val
     * @param size
     * @return
     */
    public static boolean checkAmount(BigDecimal val, int size) {

        if (val == null || val.toString().split("\\.").length <= 1) {

            return false;
        }

        if (val.toString().split("\\.")[1].length() == size) {
            return true;
        }

        return false;
    }

    /**
     * 解析百分数
     *
     * @param percent
     * @return
     */

    public static BigDecimal parsePercent(String percent, Integer mode) {
        return (percent == null || percent.length() == 0) ? BigDecimal.ZERO : new BigDecimal(percent).movePointLeft(2).setScale(2, mode);
    }

    /**
     * 解析费率
     *
     * @param percent
     * @return
     */
    public static BigDecimal parseRate(String percent, Integer scale, Integer mode) {
        return (percent == null || percent.length() == 0) ? BigDecimal.ZERO : new BigDecimal(percent).movePointLeft(2).setScale(scale, mode);
    }

    public static BigDecimal parseRate(String percent) {
        return parseRate(percent, 8, BigDecimal.ROUND_HALF_UP);
    }

}
